#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
using namespace std;
class InetAddr
{
public:
    InetAddr() {}
    InetAddr(sockaddr_in &peer)
        : _addr(peer)
    {
        _port = ntohs(peer.sin_port);
        char buffer[32];
        inet_ntop(AF_INET, &peer.sin_addr, buffer, sizeof(peer));
        _ip = buffer;
    }
    InetAddr(uint16_t port)
        : _port(port), _ip(to_string(INADDR_ANY))
    {
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }
    InetAddr(uint16_t port, string ip)
        : _port(port), _ip(ip)
    {
        _addr.sin_family = AF_INET;
        //主机序->网络序
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        //_addr.sin_addr.s_addr = inet_addr(_ip.c_str());
    }
    string tostring_port()
    {
        return to_string(_port);
    }
    string tostring_ip()
    {
        return _ip;
    }
    bool operator==(InetAddr addr)
    {
        return _port == addr._port && _ip == addr._ip;
    }
    sockaddr *getaddr()
    {
        return (sockaddr *)&_addr;
    }
    socklen_t getlen()
    {
        return sizeof(_addr);
    }
    string stringaddr()
    {
        return tostring_ip() + ":" + tostring_port() + " ";
    }

private:
    uint16_t _port;
    string _ip;
    sockaddr_in _addr;
};